package com.example.aspect;

import com.example.annotation.RateLimit;
import com.example.util.RedisUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class RateLimitAspect {

    @Autowired
    private RedisUtils redisUtils;

    @Around("@annotation(com.example.annotation.RateLimit)")
    public Object rateLimit(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        RateLimit rateLimit = method.getAnnotation(RateLimit.class);

        String key = "rate_limit:" + method.getName();
        String count = redisUtils.get(key);
        
        if (count == null) {
            redisUtils.set(key, "1", rateLimit.period());
        } else if (Integer.parseInt(count) < rateLimit.limit()) {
            redisUtils.set(key, String.valueOf(Integer.parseInt(count) + 1), rateLimit.period());
        } else {
            throw new RuntimeException("接口访问频率超限");
        }
        
        return point.proceed();
    }
} 